package com.hospital.hospitalserver.service;

import com.hospital.hospitalserver.entity.demo.MedicalDTO;
import com.hospital.hospitalserver.entity.demo.MedicalInsurance;
import com.hospital.hospitalserver.mapper.MedicalInsuranceMapper;
import com.hospital.hospitalserver.util.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;

/**
 * 模拟医保账户实现类
 * */
@Service
@RequiredArgsConstructor
public class MedicalInsuranceService {
    private final MedicalInsuranceMapper medicalInsuranceMapper;

    /**
     * 模拟查询医保二维码
     * 用于生成二维码和条形码
     * */
    public Response queryMedicalByInsuranceCardNumber(String cardNumber){
        return Response.success(medicalInsuranceMapper.queryMedicalByInsuranceCardNumber(cardNumber));
    }

    /**
     * 根据二维码卡号查询用户基础信息
     * */
    public Response queryMedicalByQrCode(MedicalDTO request){
        MedicalInsurance mi = medicalInsuranceMapper.queryMedicalByQrCode(request);
        if(mi!=null){
            return Response.success(mi);
        }else {
            return Response.error();
        }
    }

    /**
     * 根据医保卡号获取报销比例
     */
    public Double getReimbursementRate(String insuranceCardNumber) {
        return medicalInsuranceMapper.getReimbursementRate(insuranceCardNumber);
    }

    /**
     * 计算医保支付和个人支付金额
     */
    public Map<String, BigDecimal> calculateInsurancePayment(BigDecimal totalAmount, Double reimbursementRate) {
        BigDecimal insurancePayment = BigDecimal.ZERO;
        BigDecimal personalPayment = totalAmount;

        if (reimbursementRate != null && reimbursementRate > 0) {
            // 验证比例范围
            if (reimbursementRate > 100.0) {
                throw new IllegalArgumentException("报销比例不能超过100%");
            }

            // 将百分比转换为小数
            BigDecimal rateDecimal = BigDecimal.valueOf(reimbursementRate / 100.0);
            insurancePayment = totalAmount.multiply(rateDecimal)
                    .setScale(2, RoundingMode.HALF_UP);
            personalPayment = totalAmount.subtract(insurancePayment);

            // 确保个人支付不为负数
            if (personalPayment.compareTo(BigDecimal.ZERO) < 0) {
                personalPayment = BigDecimal.ZERO;
            }
        }
        return Map.of(
                "insurancePayment", insurancePayment,
                "personalPayment", personalPayment
        );
    }
}
